
<template>
	<view>
		<view>
			<form @submit="formSubmit">

			<view class="uni-form-item uni-column" style="display:none" v-if="categorys.length">
				<view class="title">类别</view>
				<picker @change="bindPickerChange" :value="index" :range="categorys" range-key="title">
					<view class="uni-input">{{categorys[index].title}}</view>
				</picker>
			</view>

			<view class="uni-form-item uni-column">
				<view class="title">标题</view>
				<input v-model="form.title" class="uni-input" placeholder="输入标题" />
			</view>

			<view class="uni-form-item uni-column">
				<view class="title">正文</view>
				<view class="uni-textarea" style="width:96%;padding:6px 2%;">
					<textarea v-model="form.content" auto-height placeholder="输入正文内容，自动多行。" />
				</view>
			</view>

			<view class="uni-form-item uni-column">
				<view class="title">上传图片(最多允许9张)</view>
				<view class="uni-uploader__files" style="padding:6px 2%;background: #FFF;">
					<block v-for="(image,index) in imageList" :key="index">
						<view class="uni-uploader__file">
							<image class="uni-uploader__img" :src="image" :data-src="image" @tap="previewImage"></image>
							<view :data-index="index" :data-src="image" @click="delete_img">删除</view>
						</view>
					</block>
					<view class="uni-uploader__input-box">
						<view class="uni-uploader__input" @tap="chooseImage"></view>
					</view>
				</view>
			</view>


			<view class="uni-btn-v" style="padding:9px 3%;">
				<button type="primary" formType="submit">修改</button>
			</view>
			</form>
		</view>
	</view>
</template>

<script>
	import * as API from 'server/getData'
	import { mapState } from 'vuex'
	import * as types from 'store/mutations_types'

	export default {
		data() {
			return {
				a_id: null,
				index: 0,
				imageList: [],
				categorys: [],
				form: {
					cid: '',
					title: '',
					content: '',
					attachment: []
				},
				count: 9,
				showLoadMore: false
			}
		},
		onLoad(e) {
			this.a_id = e.id
			this.initData()
		},
		computed: {
			...mapState(['user', 'token'])
		},
		methods: {
			initData() {
				this.getCategorys()
				this.getArticle()
			},
			// 获取分类栏目
			async getCategorys() {
				let res = await API.articles.fetchCategorys()
				if (res.success) {
					this.categorys = res.data.items
					this.form.cid = this.categorys[0].id
				}
			},
			async getArticle(id) {
				let res = await API.articles.fetchArticle({'id': this.a_id})
				if (res.success) {
					this.form.cid = res.data.cid
					this.form.title = res.data.title
					this.form.content = res.data.content
					this.imageList = res.data.attachment ? res.data.attachment : []
				}
				if (!res.success) {
					uni.showModal({
						title: '提示',
						content: res.message,
						showCancel: false,	
						success: function (res) {
							if (res.confirm) {
								uni.navigateBack()
							}
						}
					})
				}

			},
			bindPickerChange: function(e) {
				this.index = e.target.value
				this.form.cid = this.categorys[this.index]['id']
			},
			// 选择图片
			chooseImage: async function() {
				uni.chooseImage({
					count: this.count,
					success: (res) => {
						if (res.tempFilePaths.length >= this.count) {
							uni.showModal({content: `多于${this.count}张`})
							return false
						}
						// this.imageList = this.imageList.concat(res.tempFilePaths);
						let imagePathArr = res.tempFilePaths
						for (let item of imagePathArr) {
							uni.uploadFile({
								url: 'http://192.168.13.61:5000/api/articles/attachment',
								filePath: item,
								fileType: 'image',
								header: {'Authorization': `Bearer ${this.token['access_token']}`},
								name: 'upload',
								success: (res) => {
									let res_data = JSON.parse(res.data)
									if (res_data.success === false) {
										uni.showModal({ title: '上传失败', content: res_data.message[0], showCancel:false })
										return false
									}
									uni.showToast({ title: '上传成功', icon: 'success', duration: 1000 })
									this.form.attachment.push(res_data.id)
									this.imageList.push(res_data.url)
								},
								fail: (err) => {
									uni.showModal({
										content: '错了',
										showCancel: false
									});
								}
							})
						}
					}
				})
			},
			delete_img: async function (e) {
				this.imageList.splice(e.target.dataset['index'], 1)
				let id = e.target.dataset['src'].split('#')[1]
				if (id) {
					let res = await API.articles.del_attachment({'id': id})
					this.form.attachment.pop(id)
				}
			},
			formSubmit: async function() {
				this.form.attachment = JSON.stringify(this.form.attachment)
				let res = await API.articles.updateArticle(this.a_id, this.form)
				let _this = this
				if (res.success) {
					uni.showToast({title: '添加成功', duration: 2000})
					setTimeout(function () {
						_this.$store.commit(types.UPDATE_REFRESH, {'is_refresh': true})
						uni.switchTab({
							url: '/pages/articles/index'
						})
					}, 2000)
				}
				if (!res.success) {
					uni.showModal({
						title: '提示',
						content: res.message,
					});
				}
			},
			// 预览图片
			previewImage: function(e) {
				var current = e.target.dataset.src
				uni.previewImage({
					current: current,
					urls: this.imageList
				})
			},
			GMTToStr(time){
				let date = new Date(time)
				let Str=date.getFullYear() + '-' +
				(date.getMonth() + 1) + '-' +
				date.getDate() + ' ' +
				date.getHours() + ':' +
				date.getMinutes() + ':' +
				date.getSeconds()
				return Str
			}
		}
	}
</script>

<style>
uni-view {
	font-size: 28upx;
}
page {
	height: auto;
	min-height: 100%;
}
.color-red {
	color: red;
}
.uni-uploader__file {
	display: flex;
    flex-direction: column;
    align-items: center;
	height: 140px;
}
.list {}
.list-cell{padding:11px 15px;background:#fff;border-bottom:1px solid #eee;}
.list-cell .list-cell-image image{width:150upx; height:120upx; margin-right: 10px;}
.list-cell .list-cell-body{flex:1;justify-content:space-around;font-size:32upx;}
.body-title{line-height: 18px;height:37px;display: flex;
    justify-content: space-between;}
.body-footer{color: #8f8f94;justify-content: space-between;}

.info-box{
	display: flex;
	justify-content: space-between;
	align-items: center;
	height: 3em;
	text-align: center;
}
.info-box .info-box-item {
	flex:auto;
	font-size: 32upx;
}
.badge {
    display: inline-block;
    padding: .25em .4em;
    font-size: 75%;
    font-weight: 700;
    text-align: center;
    white-space: nowrap;
    vertical-align: baseline;
    border-radius: .25rem;
    transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
.badge-secondary {
    color: #fff;
    background-color: #6c757d;
}
.badge-danger {
    color: #fff;
    background-color: #FF5722;
}
</style>
